import type { ApiRes } from '../types/data'
import { useUserStore } from '../stores/user'

const BASEURL = 'https://huangjiangjun.top:3002/api/'

type RequestOption = {
	url : string
	method ?: 'GET' | 'POST' | 'PUT' | 'DELETE'
	header ?: any
	data ?: object
}

function request<T>({ url, method = 'GET', header = {}, data = {} } : RequestOption) {
	return new Promise<ApiRes<T>>((resolve, reject) => {
		const store = useUserStore()
		if (store.token) {
			header.token = store.token
		}

		uni.request({
			url: `${BASEURL}${url}`,
			method: method,
			data,
			header,
			success: res => {
				if (res.statusCode === 401) {
					// 清除token
					store.setToken('')

					// 跳转到登录页面
					// getCurrentPages() 获取到当前的页面栈
					const routeArray = getCurrentPages()
					uni.reLaunch({
						url: `/subpkg/login/login?redirect=${routeArray[routeArray.length - 1].$page.fullPath}`
					})
				} else {
					resolve(res.data as ApiRes<T>)
				}
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

export default request